package models

import (
	"github.com/astaxie/beego/orm"
	_ "github.com/mattn/go-sqlite3"
	"os"
	"path"
	"time"
)

const (
	_DB_NAME        = "data/teamcoop.db"
	_SQLITE3_DRIVER = "sqlite3"
)
const (
	TYPE_NULL     = 0
	TYPE_TODO     = 1
	TYPE_COMMENT  = 2
	TYPE_ANNOUNCE = 3
)

//数据库模型
type Todo struct {
	Id     int64     `orm:"pk;auto"`
	UserId int64     `orm:""`                            //创建者用户ID
	Time   time.Time `orm:"auto_now_add;type(datetime)"` //添加日期
	Text   string    `orm:"size(1024)"`                  //内容
	Done   bool      `orm:"default(0)"`                  //TODO完成
	Level  int8      `orm:"default(0)"`                  //级别
}
type Dynamic struct {
	Id        int64 `orm:"pk;auto"`
	Type      int8  `orm:"default(0)"` //动态类型
	TodoId    int64 `orm:""`           //todo id
	CommentId int64 `orm:""`           //评论ID
}
type Announce struct {
	Id     int64     `orm:"pk;auto"`
	UserId int64     `orm:""`                            //创建者用户ID
	Time   time.Time `orm:"auto_now_add;type(datetime)"` //创建日期
	Text   string    `orm:"size(1024)"`                  //内容
}
type Comment struct {
	Id         int64     `orm:"pk;auto"`
	UserId     int64     `orm:""`                            //创建者用户ID
	Time       time.Time `orm:"auto_now_add;type(datetime)"` //创建日期
	Text       string    `orm:"size(1024)"`                  //评论内容
	Type       int8      `orm:"null`                         //类型
	AnnounceId int64     `orm:"null"`                        //广播ID
	TodoId     int64     `orm:"null"`                        //TODO ID
}
type User struct {
	Id    int64  `orm:"pk;auto"`
	Class int8   `orm:""`                //用户等级
	Nick  string `orm:"size(64);unique"` //昵称
	Email string `orm:"size(64);unique"` //注册邮箱
	Pwd   string `orm:"size(40)"`        //账户密码
}

var is_init bool = false

//初始化
//数据库驱动注册
//设置和同步orm
func ModelInit(db_name string) {
	if is_init == true {
		return
	}
	if db_name == "" {
		db_name = _DB_NAME
	}

	if _, err := os.Stat(db_name); err != nil {
		os.MkdirAll(path.Dir(db_name), os.ModePerm)
		os.Create(db_name)
	}
	orm.RegisterModel(new(Todo), new(Dynamic), new(Comment), new(User), new(Announce))
	orm.RegisterDataBase("default", _SQLITE3_DRIVER, db_name, 10)
	orm.Debug = true
	orm.RunSyncdb("default", false, true)
	is_init = true
}
